<template>
  <el-dialog
    :title="form.id ? lang.t('common.update') : lang.t('common.create')"
    v-model="show"
    :width="800"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top" @submit.prevent="alert('a')">
      <el-tabs>
        <el-tab-pane :label="plugin.lang('form.tab.0')" name="0">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="plugin.lang('form.code')" prop="code">
                <el-input v-model="form.code" ref="input"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="plugin.lang('form.number')" prop="number">
                <el-input v-model="form.number"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="plugin.lang('form.name')" prop="name">
                <el-input v-model="form.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="plugin.lang('form.menu_id')">
                <div style="width: 100%; overflow: hidden; text-align:left">
                  <el-select v-model="form.menu_id" placeholder=" " style="width: 100%">
                    <el-option :label="plugin.lang('menu.no')" :value="0" />
                    <el-option
                      v-for="item in menuModel.getList()"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item :label="plugin.lang('form.tax_id')">
                <div style="width: 100%; overflow: hidden; text-align:left">
                  <el-select v-model="form.tax_id" placeholder=" " style="width: 100%">
                    <el-option label="-" :value="0" />
                    <el-option
                      v-for="item in taxModel.getList()"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="plugin.lang('form.price')" prop="price">
                <div style="width: 100%; overflow: hidden; text-align:left">
                  <el-tooltip effect="dark" :content="plugin.lang('form.price_message', priceData)" :trigger-keys="[]" placement="bottom-start">
                    <el-input v-model="form.price" @focus="(e) => e.target.select()" @keyup.enter="onUpdate">
                      <template #suffix>
                        <i class="iconfont icon-leftarrow" style="cursor: pointer" @click="onPriceMath()" />
                        <i class="iconfont icon-right-arrow" style="cursor: pointer" @click="onPriceMath(true)" />
                      </template>
                    </el-input>
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="plugin.lang('form.price_discount')">
                <div style="width: 100%; overflow: hidden; text-align:left">
                  <el-input-number v-model="form.price_discount" @focus="(e) => e.target.select()" :min="0" :precision="2" style="width: 100%" controls-position="right" @keyup.enter="onUpdate" />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="plugin.lang('form.price_cost')">
                <div style="width: 100%; overflow: hidden; text-align:left">
                  <el-tooltip effect="dark" :content="plugin.lang('form.price_cost_message')" :trigger-keys="[]" placement="bottom-start">
                    <el-input v-model="form.price_cost" @focus="(e) => e.target.select()" @keyup.enter="onUpdate">
                      <template #suffix>
                        <i class="iconfont icon-leftarrow" style="cursor: pointer" @click="onPriceCost()" />
                      </template>
                    </el-input>
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane :label="plugin.lang('form.tab.1')" name="1">
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item :label="plugin.lang('form.image')">
                <div style="width: 100%; overflow: hidden;">
                  <Upload v-model="form.image">
                    <template #default="scope">
                      <el-avatar v-loading="scope.loading" shape="square" :size="200" :src="app.img(form.image)" fit="cover" @click="scope.click()">
                        <div class="upload flash">
                          <i class="iconfont icon-add-max"></i>
                        </div>
                      </el-avatar>
                    </template>
                  </Upload>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item :label="plugin.lang('form.sname')">
                <el-input v-model="form.sname"></el-input>
              </el-form-item>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="plugin.lang('form.supplier_id')">
                    <el-select v-model="form.supplier_id" filterable remote :remote-method="onSupplier" :loading="supplier.loading" style="width: 100%">
                      <el-option
                        label="-"
                        :value="0"
                      />
                      <el-option
                        v-for="item in supplier.list"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="plugin.lang('form.append')">
                    <el-select v-model="form.append" style="width: 100%">
                      <el-option
                        v-for="(item, index) in plugin.langTm('form.append_text')"
                        :label="item"
                        :value="index"
                        :key="index"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="plugin.lang('form.unit')">
                    <el-input v-model="form.unit"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="plugin.lang('form.unit_count')">
                    <div style="width: 100%; overflow: hidden; text-align:left">
                      <el-input-number v-model="form.unit_count" :min="0" style="width: 100%" controls-position="right" />
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="plugin.lang('form.count_max')">
                    <div style="width: 100%; overflow: hidden; text-align:left">
                      <el-input-number v-model="form.count_max" :min="0" style="width: 100%" controls-position="right" />
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="plugin.lang('form.count_min')">
                    <div style="width: 100%; overflow: hidden; text-align:left">
                      <el-input-number v-model="form.count_min" :min="0" style="width: 100%" controls-position="right" />
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <template v-if="form.id">
          <el-button type="primary" :loading="loading" @click="onUpdate">{{ lang.t('common.update') }}</el-button>
        </template>
        <template v-else>
          <el-button type="primary" v-if="createType == 0" :loading="loading" @click="onUpdate">{{ lang.t('common.oneCreate') }}</el-button>
          <el-button type="success" v-if="createType == 1" :loading="loading" @click="onUpdate">{{ lang.t('common.toCreate') }}</el-button>
          <el-button type="warning" v-if="createType == 2" :loading="loading" @click="onUpdate">{{ plugin.lang('inbound.btn.create') }}</el-button>
        </template>
      </span>
    </template>
  </el-dialog>
  <Import ref="importRef" :form="importForm" @load="importLoad" @over="model.get()"></Import>
</template>
<script>
import { ref, reactive,nextTick } from 'vue'
import app from '@/app'
import model from '../../model'
import menuModel from '../../model/menu'
import createModel from '../../model/create'
import taxModel from '@/plugin/config/model/tax'
import configModel from '@/plugin/config/model'
import { get } from '@/api/store/goods'
import { get as getSupplier } from '@/api/erp/supplier'

import Upload from '@/components/upload'
import Import from '@/components/import'

export default {
  components: {
    Upload,
    Import
  },
  setup() {
    // 插件
    const plugin = app.plugin.index

    // 对话框
    const show = ref(false)

    // 表单
    const formRef = ref(null)
    const form = ref({})
    const priceData = reactive({
      tax: 0,
      price: 0
    })

    // 验证
    const rules = {
      name: [
        { required: true, message: ' ', trigger: 'blur' }
      ],
      number: [
        { required: true, message: ' ', trigger: 'blur' }
      ],
      code: [
        { required: true, message: ' ', trigger: 'blur' }
      ],
      price: [
        { required: true, message: ' ', trigger: 'blur' }
      ]
    }

    // 创建方式 
    const createType = ref(0)
    // 首个输入框焦点
    const input = ref()

    // 打开
    const open = (data, create = 0) => {
      createType.value = parseInt(create)

      data.price = Number(data.price) || 0
      data.price_discount = Number(data.price_discount) || 0
      data.price_cost = Number(data.price_cost) || 0

      // 默认税率
      if(data.tax_id == undefined) {
        data.tax_id = taxModel.default()?.id
      }

      form.value = Object.assign({}, data)
      show.value = true

      onPriceTax()
      onSupplier()

      nextTick(() => setTimeout(() => input.value.focus(), 500))
    }

    // 更新
    const loading = ref(false)
    const onUpdate = () => {
      formRef.value.validate(valid => {
        if (valid) {
          loading.value = true
          model.update(form.value).then(() => {
            // 判断创建方式
            if(createType.value > 0) {
              // 再次打开
              open({}, createType.value)
              // 入库操作
              if(createType.value > 1) {
                get().then(res => {
                  createModel.add(res.data[0]);
                })
              }
            } else {
              show.value = false
            }
            
          }).finally(() => {
            loading.value = false
          })
        }
      })
    }

    // 导入组件
    const importRef = ref(null)

    // 打开导入
    const importOpen = () => {
      // 清空清单数据，因为共用一个对象
      form.value = {}
      importRef.value.open()
    }

    // 导入表单
    const importForm = {
      code: plugin.lang('form.code'),
      number: plugin.lang('form.number'),
      name: plugin.lang('form.name'),
      price: plugin.lang('form.price'),
      menu_id: plugin.lang('form.menu_id'),
      tax_id: plugin.lang('form.tax_id'),
      count: plugin.lang('form.count'),
      sname: plugin.lang('form.sname'),
      price_discount: plugin.lang('form.price_discount'),
      price_cost: plugin.lang('form.price_cost'),
      unit: plugin.lang('form.unit'),
      unit_count: plugin.lang('form.unit_count'),
      count_min: plugin.lang('form.count_min'),
      count_max: plugin.lang('form.count_max'),
    }

    // 开始导入
    const importLoad = () => {
      importRef.value.load(data => {
        return new Promise((resolve) => {
          // 检查分类
          if(data.menu_id) {
            data.menu_id = menuModel.name(data.menu_id)?.id ?? 0
          }
          if(data.tax_id) {
            data.tax_id = taxModel.name(data.tax_id)?.id ?? 0
          }
          model.cover(data).then(() => {
            resolve(true)
          }).finally(() => {
            resolve(false)
          })
        })
      })
    }

     // 推算价格
    const onPriceMath = (type = false) => {
      const func = type ? app.math.addpro : app.math.divpro

      onPrice(func(
        form.value.price, 
        taxModel.tax(form.value.tax_id)
      ))
    }

    // 更新价格
    const onPrice = price => {
      form.value.price = price ?? 0
      onPriceTax()
    }

    const onPriceTax = () => {
      if(configModel.taxType()) {
        priceData.tax = app.math.sub(
          form.value.price,
          app.math.divpro(form.value.price, taxModel.tax(form.value.tax_id))
        )
        priceData.price = form.value.price
      } else {
        priceData.tax = app.math.pro(form.value.price, taxModel.tax(form.value.tax_id))
        priceData.price = app.math.add(form.value.price, priceData.tax)
      }
      
      priceData.tax = app.money(priceData.tax)
      priceData.price = app.money(priceData.price)
    }

    // 成本价回推
    const onPriceCost = () => {
      form.value.price_cost = app.math.factory(form.value.price_cost).divpro(
        taxModel.tax(form.value.tax_id)
      ).format(4)
    }

    // 选择供货商
    const supplier = reactive({
      list: [],
      loading: false
    })
    const onSupplier = (name) => {
      supplier.loading = true
      getSupplier({ name }).then(res => {
        supplier.list = res.data
      }).finally(() => supplier.loading = false)
    }

    return {
      app,
      lang: app.lang,
      plugin,
      show,
      createType,
      input,
      open,
      model,
      formRef,
      form,
      rules,
      loading,
      onUpdate,
      menuModel,
      taxModel,
      importRef,
      importOpen,
      importForm,
      importLoad,
      priceData,
      onPriceMath,
      onPriceCost,
      supplier,
      onSupplier
    }
  }
}
</script>